<script setup>
import { ref, reactive, toRaw } from "vue"
import { service, cache } from "@utils"
import { ElMessage } from "element-plus"

const emit = defineEmits(["refresh"])

defineProps({
  types: Array,
})

const visible = ref(false)
const formRef = ref()

const state = reactive({
  param: {},
})

const rules = {
  label: [{ required: true, message: "请输入", trigger: "blur" }],
  code: [{ required: true, message: "请输入", trigger: "blur" }],
}

const open = async (item) => {
  state.param = { ...item }
  visible.value = true
}

const close = () => {
  visible.value = false
  state.param = {}
}

const sure = async () => {
  formRef.value.validate((valid) => {
    if (valid) {
      realSubmit()
    }
  })
}
const realSubmit = async () => {
  if (!!state.param.id) {
    const res = await service.sys.dictionaryEdit(toRaw(state.param))
    if (res) {
      ElMessage.success("修改成功")
      close()
      emit("refresh", !!state.param.id)
    }
  } else {
    const res = await service.sys.dictionarySave(toRaw(state.param))
    if (res) {
      ElMessage.success("新增成功")
      close()
      emit("refresh", !!state.param.id)
    }
  }
}
//把方法暴露给父组件
defineExpose({
  open,
})
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="!!state.param.id ? '修改' : '新增'"
    center
    :close-on-click-modal="false"
    @close="close"
    destroy-on-close
    :width="500"
  >
    <section>
      <el-form
        :model="state.param"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        label-suffix=":"
        onsubmit="return false;"
      >
        <el-form-item label="字典名称" prop="name">
          <el-input
            v-model="state.param.name"
            placeholder="请输入字典名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="字典编码" prop="typeCode">
          <el-input
            v-model="state.param.typeCode"
            placeholder="请输入字典编码"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
    </section>

    <template #footer>
      <span class="flex-align-end">
        <div class="margin-right20">
          <el-button @click="close">取消</el-button>
        </div>
        <el-button type="primary" @click="sure">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
